import './assets/styles/global.css'
import {createApp} from 'vue'
import {createPinia} from "pinia";
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import App from './App.vue'
import router from '@/router/index.js'
import {initGlobalErrorHandler} from '@/utils/errorHandler.js'

// 导入 Element Plus 和相关样式
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

// 拦截 ResizeObserver 错误
const resizeObserverErr = window.console.error;
window.console.error = (...args) => {
    if (args[0] && typeof args[0] === 'string' && args[0].includes('ResizeObserver')) {
        // 阻止webpack-dev-server显示overlay错误提示
        if (typeof Event !== 'undefined') {
            window.dispatchEvent(new Event('error'));
        }
        return;
    }
    
    // 屏蔽 passive event listener 警告
    if (args[0] && typeof args[0] === 'string' && args[0].includes('[Violation] Added non-passive event listener')) {
        return;
    }
    
    resizeObserverErr(...args);
};

const app = createApp(App)
const pinia = createPinia()

// 注册插件
pinia.use(piniaPluginPersistedstate)

// 安装 pinia
app.use(pinia)

import {useUserStore} from '@/stores/pages/user'
import {useTabsStore} from "@/stores/tabs.js";

const userStore = useUserStore()
const tabsStore = useTabsStore()

// 先初始化用户状态（必须在路由守卫之前）
userStore.initUserState()

// 再初始化标签页
tabsStore.initTabs()

// 安装 Element Plus
app.use(ElementPlus)

// 安装路由和其他设置
app.use(router)

// 全局后置守卫(2)
router.afterEach((to, from) => {
    // 排除错误页面，避免将错误页面存入标签
    const isErrorRoute = to.path === '/500' ||
        to.path === '/403' ||
        to.path === '/404' ||
        to.path === '/auth/login' ||
        to.path.startsWith('/:pathMatch') ||
        to.name === 'not-found' ||
        to.name === 'server-error'

    if (!isErrorRoute) {
        tabsStore.addTab({
            path: to.path,
            title: to.meta.title || to.name?.toString() || '未命名',
            meta: to.meta
        })
    }
    tabsStore.setActiveTab(to.path)
})

// 全局错误处理
app.config.errorHandler = (error, instance, info) => {
    console.error('[Vue Error]', error, instance, info)
}

app.config.warnHandler = (msg, instance, trace) => {
    console.warn('[Vue Warning]', msg, instance, trace)
}

// 初始化全局错误处理
initGlobalErrorHandler()

// 最后挂载应用
app.mount('#app')